<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>在线考试系统后台</title>
    <link rel="icon" href="favicon.ico" type="image/ico">
    <meta name="keywords" content="模板">
    <meta name="description" content="在线考试系统后台">
    <meta name="author" content="SoulCoder">
    <div th:include="~{views/common/include :: cssStyle }"></div>
    <style>
        [name='roleId'] {
            font-size:16px;
            height:28px;
            width:180px;
            cursor:pointer;
            margin-left:8px;
        }
        [name='roleId'] > option{
            background: #F5F5F5;
            cursor:pointer;
        }
    </style>
</head>

<body>
<div class="coder-layout-web">
    <div class="coder-layout-container">

        <!--左侧导航-->
        <div th:include="~{views/common/include :: #asideStyle }"></div>
        <!--END 左侧导航-->
        <!--头部信息-->
        <div th:include="~{views/common/include :: #headerStyle }"></div>
        <!--END 头部信息-->
        <!--页面主要内容-->
        <main class="coder-layout-content">

            <div class="container-fluid">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-toolbar clearfix">
                                <!-- 查询搜索框 [ START ]-->
                                <div id="toolbar">
                                    <div class="my-container">
                                        <label class="myLabel-content">名称: </label>
                                        <div class="myText-content">
                                            <input id="q_username" name="username" type="text" class="form-control" placeholder="输入名称">
                                        </div>
                                    </div>
                                    <div class="my-container">
                                        <label class="myLabel-content">邮件: </label>
                                        <div class="myText-content">
                                            <input id="q_email"  name="email"   type="text" class="form-control" placeholder="输入邮件">
                                        </div>
                                    </div>
                                    <div class="myBtn-content"><!--data-method="search" 定义了search方法 然后事件绑定 再就是方法体-->
                                        <button id="search" type="button" class="btn btn-primary" data-toggle="modal" data-method="search">
                                            <i class="mdi mdi-account-search"></i>搜索</button>
                                    </div>
                                </div>
                                <!-- 查询搜索框 [END]-->

                                <!-- 按钮区 [START] -->
                                <div class="toolbar-btn-action">
                                    <!--sec:authorize= "hasRole('管理员') 只有管理员有此权限
                                    点击新增 触发按钮 基于绑定的 add 事件，调用 add 方法
                                    -->
                                    <button sec:authorize="hasRole('admin')" type="button"
                                            class="btn btn-primary" data-toggle="modal" data-method="add" >
                                        <i class="mdi mdi-plus"></i>新增
                                    </button>
                                    <!--sec:authorize="hasRole('admin') 只有管理员有此权限
										点击新增 触发按钮 基于绑定的add事件，调用delBatch方法  data-method="delBatch
                                    -->
                                    <button sec:authorize="hasRole('admin')" type="button"
                                            class="btn btn-primary" data-toggle="modal" data-method="delBatch" >
                                        <i class="mdi mdi-window-close"></i>批量删除
                                    </button>
                                    <!--<a class="btn btn-pink" href="#!" data-method="addUserRole"><i class="mdi mdi-plus"></i>设定角色</a>-->
                                    <!--<a class="btn btn-info" href="#!"><i class="mdi mdi-window-close"></i> 导入</a>-->
                                    <!--<a class="btn btn-pink" href="#!"><i class="mdi mdi-window-close"></i> 导出</a>-->
                                    <!--<a class="btn btn-cyan" href="#!" data-method="popChart"><i class="mdi mdi-search-web"></i> 报表</a>-->
                                </div>
                                <!-- 按钮区 [END] -->

                            </div>

                            <div class="card-body">
                                <div class="table-responsive">
                                    <table id="userTable" ></table>
                                </div>
                            </div>

                            <!--
                                 新增表单 [START]
                                 [1]class="modal fade" {即对话框}
                                 [2]对话框ID="userModal"
                              -->
                            <div class="modal fade" id="userModal" tabindex="-1"
                                role="dialog" aria-labelledby="modalLabel"
                                th:include="~{views/user/user_form :: #userFormDiv }" >
                            </div>
                            <!-- 新增表单结束-->

                            <!-- [I] 修改表单 [START] id="userEditModal" -->
                            <!-- {已废弃} -->
                            <!-- 修改表单 [END]-->

                            <!-- [II] 设定角色 [start] -->
                            <!-- {已废弃} -->
                            <!-- 设定角色 [END]-->

                        </div>
                    </div>
                </div>
            </div>

        </main>
        <!-- [ END ] 页面主要内容 -->
    </div>
</div>

<div th:include="~{views/common/include :: #jsStyle}"></div>
<script type="text/javascript"  th:src="@{/static/js/jquery.serialize-object.min.js}"></script>
<script type="text/javascript"  th:src="@{/static/js/confirm.js}"></script>
<script type="text/javascript"  th:src="@{/static/js/my-ajax.js}"></script>
<script type="text/javascript"  th:src="@{/static/js/my-form.js}"></script>

<!-- {3}Javascript 专区 -->
<div th:include="~{views/user/user_validate :: userValidate }"></div>
<div th:include="~{views/user/file_upload :: fileUpload }"></div>
<div th:include="~{views/user/user_table :: userTable }"></div>


<script>
    var role_map = {
        admin: 1,
        teacher: 2
    };
    function getRoleId( roleName ) {
        var roleId = role_map[ roleName ];
        if( roleId ) return roleId;
        return '';
    }
</script>


<!--图表插件-->
<script type="text/javascript" th:inline="javascript">
    //全局变量:
    var ctxPath = [[${#httpServletRequest.getContextPath()}]];
    var opMODE = 'ADD';  //ADD(默认) | EDIT

    $( document ).ready(
        function( e ){
        $('#userTable').bootstrapTable
        (
            getTableSettings()
        );    //bootstrapTable [END]
        console.log( "[tableSettings]" );
    } );    //$(document).ready

    var ADD_VIEWS = [
        {name:'username',show:1},
        {name:'email',show:1},
        {name:'tel',show:1},
        {name:'password',show:1},
        {name:'confirmPassword',show:1},
        {name:'roleId',show:1},
        {name:'sex',show:1},
        {name:'file',show:1},
    ];
    var EDIT_VIEWS = [
        {name:'username',show:1},
        {name:'email',show:1},
        {name:'tel',show:1},
        {name:'password',show:0},
        {name:'confirmPassword',show:0},
        {name:'roleId',show:1},
        {name:'sex',show:1},
        {name:'file',show:0},
    ];

    //2. 点击编辑按键时触发.
    function edit( id ){
        opMODE = 'EDIT';        
        $("#modalLabel").html("编辑用户");
		showViews( EDIT_VIEWS );

        //(1)弹出修改的表单
        $("#userModal").modal({show:true})
        //(2)数据的回显操作{清空表单数据}
        $('#userForm')[0].reset();
        //(3)获取选中一行数据 根据id 获取行数据
        var row = $("#userTable").bootstrapTable('getRowByUniqueId',id);
        var F = ['id','username','email','tel'];
        setForm(F, "frm_", row);

        var roleName = row.roleName;
        var roleId = getRoleId( roleName );
        $("#frm_roleId").val( roleId );

        var sexVal = row.sex
        if( row.sex=='男' ){
            $("#frm_sex_gen").prop("checked",true);
        }else{
            $("#frm_sex_lady").prop("checked",true);
        }
    }

    //3. 点击删除按键时触发.
    function del( id ){
        confirmSEL("你真的忍心删除我吗?",
            function () {
                //1. 根据 [id] 删除数据
                deleteJSON({
                    url: ctxPath +"/System/User/deleteUser/"+ id,
                    success: onDeleteUserResp
                });
            }
        );
        function onDeleteUserResp( resp ){
            if( resp.result=="success" ){
                confirmOK("删除用户 ["+ id +"] 成功");
                $("#userTable").bootstrapTable('refresh');
            }else{
                confirmFail(
                    "删除用户 ["+ id +"] 的失败,"+
                    "原因:"+ resp.cause );
            }
        }
    }  //[ del END ]


    /* add 新增方法 */
    var userId ;
    $( document ).ready(
        function( e ) {
            //绑定事件 <button data-method='add'><a data-method='search'>
            $("button,a").on('click',function(){       //button或者a标签都可以
                let mtdName = $(this).data('method');  //this 相当于button method方法名即add
                if( mtdName ){
                    //动态调用方法 doMethod[ mtdName ]();
                    doMethod[ mtdName ]();
                }
            });

            /* 声明变量 doMethod */
            var ADD_FLDS  = ['username','email','tel','password','roleId']; /* 特殊项:sex */
            var EDIT_FLDS = ['id','username','email','tel','roleId'];       /* 特殊项:sex */

            var doMethod = {
                //条件用户角色弹框
                addUserRole:function(){
                    //判断用户是否选中的数据, 如果没有选中 给予提示
                    //(要弹出对话框，所以要获取 id 为 userTable  getSelections为选中的)
                    let rows =  $("#userTable").bootstrapTable('getSelections');
                    if(rows.length <= 0 ){
                        confirmOK( '亲 请选中一行数据进行操作' );
                        return;
                    }
                    //弹出设置权限对话框
                    $("#addUserRoleModal").modal({show:true})
                    //回显数据操作
                    $("#addRole_userid").val(rows[0].id)
                    $("#addRole_username").val(rows[0].username)
                    let roles = rows[0].roles
                    //先情况所有的多选框数据
                    $("input[name='roles[]']").prop('checked',false)
                    //设置权限
                    roles.forEach((role,index)=>{
                        var rid = role.id;
                    $("#rid_"+rid).prop('checked',true);
                });
                },

                addUserRoleSave(){
                    //保存用户角色 获取表单数据
                    var urParamObj = $("#addUserRoleForm").serializeObject()
                    var sendParam = {
                        "userId": urParamObj.id,
                        "roleIds": urParamObj.roles
                    };
                    /* 去除代码 [001] */
                },

                popChart:function(){
                    //userChartModal
                    $('#userChartModal').modal({
                        show: true,
                        backdrop:'static'
                    });
                },

                /*
                 * 用户列表--批量删除
                 */
                delBatch:function(){
                    //(1)获取表格里面 选中的所有行数据
                    let delRows = $("#userTable").bootstrapTable('getSelections');
                    if( delRows.length<=0 ){
                        confirmOK('亲,请选中至少一行数据进行删除.');
                    }else{
                        //有选中数据
                        $.confirm({
                            title:'温馨提示',
                            content:'亲，您真的忍心把我删除掉吗?',
                            type:'green',
                            buttons:{
                                omg:{
                                    text:'确定',
                                    btnClass:'btn-green',
                                    action:function(){
                                        //(1)声明空数组 ids 来存储你选中数据
                                        var ids = [];    //ids = [1,2,3]
                                        for(var i=0; i<delRows.length; i++){
                                            ids.push(delRows[i].id);
                                        }
                                        //(3)向后台发送 ajax 请求删除数据
                                        $.ajax({
                                            url:'/System/User/deleteBatchUser',
                                            type:'post',
                                            data:{"ids":ids},//键值对  ids为数组，把选中的id传到后台
                                            success:function( resp ){  //(4)判断后台返回结果
                                                if( resp.result=="success" ){
                                                    $("#userTable").bootstrapTable('refresh')
                                                }
                                            }
                                        });
                                    }
                                },
                                close:{
                                    text:'取消'
                                }
                            }
                        })
                    }
                },

                //(1)点击新增时触发
                add:function(){
                    //展示用户操作对话框 [表单]
                    opMODE = 'ADD';					
                    $("#userModal").modal({
                        show:true
                    });
					$("#modalLabel").text("新增用户");
					showViews( ADD_VIEWS );
					clearValues(ADD_FLDS, "frm_");
                },

                search:function(){
                    var F = ['username','email'];
                    var obj = pickSearchData( F,"q_" );
                    var queryParam = {
                        query: obj
                    }
                    $('#userTable').bootstrapTable('refresh',queryParam);
                },

                /* -------------- {1} [新增用户操作] ---------------- */
                save:function(){
                    //(1)获取验证框数据 {检测是否验证通过}
                    var validator = $('#userForm').data('bootstrapValidator');
                    validator.validate();       //validate()返回的数据
                    if( validator.isValid() ){  //isValid()即validate()返回数据[true]
                        if( opMODE=='ADD' ){
                            this.addSave( pickData(ADD_FLDS,"frm_") );
                        }else{
                            this.editSave( pickData(EDIT_FLDS,"frm_") );
                        }
                    }
                },   //save:function() [END]..

				//{1}新增用户保存操作 {ADD_CODE}
                addSave:function( formObj ){
                    var sex = getRadioValue('sex');
                    formObj['sex'] = sex;
                    //A.添加处理逻辑开始..
                    postJSON({
                        url: ctxPath +"/System/User/addUser",
                        data: formObj,
                        success: onAddUserResp
                    });
                    //B.添加处理逻辑结束 [END]..
                    function onAddUserResp(resp) {
                        if( resp.result=='success' ){
                            userId = resp.userId;
                            if( $('#file-pic').val()!=null ){
                                $('#file-pic').fileinput('upload');
                            }
                            $('#userModal').modal('hide');
                            $('#userTable').bootstrapTable('refresh');
                            confirmOK('添加用户成功。');
                        }else{
                            confirmFail('添加用户失败, 原因:'+ resp.cause);
                        }
                    }
                },

                //{2}修改保存操作 {EDIT_CODE}
                editSave:function( formObj ){
					var sex = getRadioValue('sex');
                    formObj['sex'] = sex;
                    //{2.1}发送一个更新请求到 Controller
                    postJSON({
                        url: ctxPath +"/System/User/updateUser",
                        data: formObj,
                        success: updateUserResp
                    });
                    //{2.2}updateUserResp函数
                    function updateUserResp(resp){
                        if( resp.result=="success" ){
                            $("#userModal").modal("hide");
                            $("#userTable").bootstrapTable("refresh");
                            confirmOK("更新用户成功。");
                        }else{
                            confirmFail("更新用户失败, 原因:"+ resp.cause);
                        }
                    }
                }      //[ editSave:END ]

            }    /*----------- doMethod() [END] -----------*/

			//{10}文件上传事件初始化..
			fileUploadInit();

            //验证规则 --- 由 bootstrap 框架提供
            $('#userForm').bootstrapValidator( rules );

        });
</script>

<style>
    .my-container {
        float: left;
        display: inline-block;
        margin-right:30px;
    }
    .myLabel-content ,.myText-content,.myBtn-content{
        float: left;
        display: inline-block;
        line-height: 40px;
        margin-left: 10px;
    }
    .myLabel-content,.myText-content input[type='text'],.myBtn-content .btn {
        height: 38px;
        font-size: 15px;
    }
    .myBtn-content .btn {
        margin-bottom: 10px;
        margin-right: 20px;
    }
</style>

</body>
</html>